package com.easy.project.base.exception;

import com.easy.project.base.result.IBaseErrorCode;

/**
 * 业务异常类
 * @author wxz
 */
public class ServiceException extends RuntimeException implements IBaseErrorCode {

    private String code;
    private String msg;

    public ServiceException(IBaseErrorCode baseErrorCode) {
        super(baseErrorCode.getMsg());

        this.code = baseErrorCode.getCode();
        this.msg = baseErrorCode.getMsg();
    }

    public ServiceException(IBaseErrorCode baseErrorCode, Object... args) {
        super(mergeCodeMsg(baseErrorCode.getCode(), formatMsg(baseErrorCode.getMsg(), args)));

        this.code = baseErrorCode.getCode();
        this.msg = formatMsg(baseErrorCode.getMsg(), args);
    }

    public ServiceException(String code, String msg) {
        super(mergeCodeMsg(code, msg));

        this.code = code;
        this.msg = msg;
    }

    public ServiceException(String code, String msg, Object... args) {
        super(mergeCodeMsg(code, formatMsg(msg, args)));

        this.code = code;
        this.msg = formatMsg(msg, args);
    }

    private static String mergeCodeMsg(String code, String msg) {
        return String.format("%s %s", code, msg);
    }

    private static String formatMsg(String msg, Object... args) {
        if (msg == null) {
            return null;
        }

        return String.format(msg, args);
    }

    @Override
    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    @Override
    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

}
